package com.acoreful.menos.utils.pdftohtml;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

public class PdfToHtml {
	public static void main(String[] arguments) {
		String p = "D:\\d.pdf";

		Document document = new MyDocument();

		try {
			document.setFile(p);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		int pages = document.getNumberOfPages();

		System.out.println("pages  " + pages);

		List<String> imgPaths = new ArrayList<String>();

		BufferedImage image = null;

		RenderedImage rendImage = null;

		for (int i = 0; i < pages; i++) {
			image = (BufferedImage) document.getPageImage(i,
					GraphicsRenderingHints.SCREEN, Page.BOUNDARY_TRIMBOX, 0f,
					1.5f);
			;

			rendImage = image;

			System.out.println("/t capturing page " + i);

			File file = new File("D:\\pdfToHtml\\c_" + i + ".png");

			imgPaths.add("c_" + i + ".png");

			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}

				try {
					ImageIO.write(rendImage, "png", file);
				} catch (IOException e) {
					e.printStackTrace();
				}

				image.flush();
			} else {
				System.out.println("/t capturing page is exist !");
			}
		}

		document.dispose();

		String html = HtmlHelper.getHtml(imgPaths);

		File file = new File("D:\\pdfToHtml\\c.html");

		if (file.exists()) {
			file.delete();
		}

		try {
			FileOutputStream out = new FileOutputStream(file);

			out.write(html.getBytes());

			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println(html);
	}
}
